package com.zhongwang.business.module.estimateBudgetAccountingManage.dao;


import com.zhongwang.business.module.estimateBudgetAccountingManage.model.redis.MatDescModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author 徐一贺
 * @className SynchronizeDataDao
 * @description redis 持久层
 * @date 2020/12/16 20:45
 * @versron ver 1.0
 */
@Configuration
@Repository
public class SynchronizeDataDao {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 向redis中写入键值对
     *
     * @param key
     * @param value
     */
    public void setKey(String key, String value) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(key, value, 1, TimeUnit.DAYS);
    }
    /**  findMatDescList 从redis中获取数九
     * @param topCount 前多少条
     * @param keyStr 关键词
     * @return java.util.List<com.zhongwang.business.module.estimateBudgetAccountingManage.model.redis.MatDescModel>
     * @author 徐一贺
     * @date 2020/12/31 13:03
     */
    public List<MatDescModel> findMatDescList(int topCount,String keyStr){
        Set<String> set = stringRedisTemplate.keys("matDesc:"+keyStr+"*");
        List<MatDescModel> result = new ArrayList<>();
        List <String> list = new ArrayList<String>(set);//B是set型的
        if(list.size()<topCount){
            topCount = list.size();
        }
        for (int i = 0; i < topCount; i++) {
            MatDescModel data = new MatDescModel();
            data.setMatDesc(list.get(i));
            result.add(data);
        }
        return result;
    }
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

}
